#Create your views here.
from django.shortcuts import render_to_response
from bloganalisys.analysis.vector_analysis import *
from bloganalisys.analysis.forms import *
from couchdb import Server
from couchdb import ResourceNotFound
import cdb
SERVER = Server('http://127.0.0.1:5984')
db = SERVER[cdb.COUCH_DB]

def try_again(f):
	def opakowanie(*args, **kwds):
		try:
			return f(*args, **kwds)
		except ResourceNotFound:
			print 'nieznaleziono elementu'
			return []
		except:
			print "zlapalem wyjatek"
			return f(*args, **kwds)
	return opakowanie

@try_again
def get(id):
  return db[id]

@try_again
def zapytanie(fun):
  return db.query(fun, language="python") 


def search(texts, start):
  start_text = start
  v_a = VectorAnalysis(True, texts, start_text, False,  'X')
  return v_a.calculate()


content_fun = """def fun(doc):
    if doc['type'] == 'blog_note' and doc['context']:
      yield doc['_id'], doc"""

comment_fun = """def fun(doc):
    if doc['type'] == 'comment':
      yield doc['_id'], doc"""


content_f = """def fun(doc):
	if doc['type'] == 'blog_note':
		yield doc['date'].split(".")[1], 1"""


comment_f = """def fun(doc):
	if doc['type'] == 'comment':
		yield doc['date'].split("-")[1], 1"""

#################################################################
############
def analysis_frequency_view(request):

  print cdb.COUCH_DB
  plot_name = 'null' 
  ret = [ ("" , "") ]
  if request.method == "POST":
    form = FreqForm(request.POST)
    if form.is_valid():
	    wyn = defaultdict(int)

	    try:
	        if request.POST['comments']:
	          comments = True
	          r1 = db.query(comment_f, language='python')
			  
	          for r in r1.rows:
				print r
				wyn[r.key] += 1
	    except 'error':
				wyn = defaultdict(int)
				for r in r1.rows:
					wyn[r.key] += 1		
	    except:
	        comments = False
	        
	    try:
	        if request.POST['content']:
					content = True
						
					r2 = db.query(content_f, language='python')
					for r in r2.rows:
						wyn[r.key] += 1

	    except 'error':
					wyn = defaultdict()
					for r in r2.rows:
						wyn[r.key] += 1
	    except:
					content = False    			
	     
	    print wyn
	    from pylab import *
	    pos = arange(12) +.5
	    val = [ wyn['01'], wyn['02'], wyn['03'], wyn['04'], wyn['05'], wyn['06'], wyn['07'], wyn['08'], wyn['09'], wyn['10'], wyn['11'], wyn['12']]
	    barh(pos,val, align='center') 
	    xlabel('ilosc')
	    ylabel('miesiac')
	    yticks(pos, ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'))
	    title('Czestotliwosc pisania')
	    import random
	    plot_name = 'site_media/freq'+str(random.randint(1,1000))+'.png'
	    savefig(plot_name)
	    close()
	      
	    return render_to_response("frequency_analysis.html",  {'form' : form, 'return' :ret, 'plot_name' : plot_name} )

  form = FreqForm()


  return render_to_response("frequency_analysis.html" ,  {'form' : form, 'return' :ret, 'error' : "nieznaleziono w bazie"} )

##########################
#################################################################
def analysis_zipf_view(request):
	
  print cdb.COUCH_DB
  plot_name = 'null' 
  ret = [ ("" , "") ]
  if request.method == "POST":
    form = ZipfForm(request.POST)
    if form.is_valid():


      id = request.POST['id']

      doc = get(id)
      if not doc:

					return render_to_response("zipf_analysis.html" ,  {'form' : form, 'return' :ret, 'error' : "nieznaleziono w bazie"} )
      d = defaultdict(int)
      if doc['type'] == "blog_note":
          text = doc['context'].lower()
      elif doc['type'] == 'comment':
          text = doc['content'].lower()
      else:
          text = "brak"

      if text:
        #jesli mamy co badac:
        pat = re.compile("\W+", re.UNICODE)
        ret = []
        for slowo in pat.split(text):
          d[slowo] += 1

      
        sd = sorted(d.iteritems(), key = lambda (k,v): (v,k), reverse = True)
        
        for x in sd:
          ret.append(x)
      #print sd

      v = []
      for word, count in sd:
        v.append(count)
      r= range( len(v))

      from pylab import *
      xlabel('pozycja')
      ylabel('czestosc')
      title('Zipf')
      loglog(r, v)
      import random
      plot_name = 'site_media/zipf'+str(random.randint(1,1000))+'.png'
      savefig(plot_name)
      close()
      
      ret = filter(lambda x: x[1]>1,ret)

  form = ZipfForm()



  return render_to_response("zipf_analysis.html" ,  {'form' : form, 'return' :ret, 'plot_name' : plot_name} )


def analysis_statistic_view(request):
  ret = []
  if request.method == "POST":
    form = Statistic(request.POST)
    if form.is_valid():
      try:
        if request.POST['comments']:
          comments = True
      except:
        comments = False
        
      try:
        if request.POST['content']:
          content = True
      except:
        content = False

      query = map(lambda x: x.strip(), request.POST['query'].split(','))
      
      query_dict = {}
      for q in query:
          query_dict[q] = defaultdict(int)


      texts = []
      
      if content:
        t = zapytanie(content_fun)
        for id in t:
					try:
						texts.append( (id.key, id.value['context'].lower(), 'note') )
					except:
						texts.append( (id.key, id.value['context'].lower(), 'note') )
      if comments:
        t = zapytanie(comment_fun)
        for id in t:
					try:
						texts.append( (id.key, id.value['content'].lower(), 'comment'))
					except:
						texts.append( (id.key, id.value['content'].lower(), 'comment'))

      pat = re.compile(r'\W+', re.UNICODE)

      
      print len(texts)
      for id, text, typ in texts:
        for x in pat.split(text):
          # dla kazdefo z poszukiwanych slow
          for k in query_dict.keys():
            if x == k: # jezeli klucz jest ok
              query_dict[k][id] += 1

  
      for k in query_dict.keys():
        query_dict[k] = sorted(query_dict[k].iteritems(), key = lambda (k,v): (v,k), reverse = True)
          

      ret = []
      for k in query_dict.keys():
        ret.append( (k, 0) )

        for i in range(20):
          try:
            ret.append( query_dict[k][i] )
          except IndexError:
            pass

      #print query_dict[k]
#        for i in query_dict[k].keys():
#          print i, query_dict[k][i]

      
     
      #ret = [id, counter]
      #print ret
      #print comments, content, query
      

  form = Statistic()
  
  return render_to_response('statistic_analysis.html', {'form' : form, 'return' : ret} )


def analysis_view(request):
  

  return render_to_response('analysis.html', {})

def analysis_vector_view(request):


  texts = []
  blog_note = ""

  # pobierz wszystkie wpisy:
  fun = """def fun(doc):
    try:
      if doc['type'] == 'blog_note' and doc['context']:
        yield doc['topic'], doc
    except:
      pass"""

  t = zapytanie(fun)

  for id in t:
    texts.append( (id.key, id.value['_id'], id.value['context']) )

  
  
  find_fun = """def fun(doc):
          if doc['type'] == 'blog':
              yield doc['blog_name'], doc"""

  if request.method == "POST":
    form = BlogForm(request.POST)
    if form.is_valid():
      blog_note = request.POST['blog_note']
      #print unicode(blog_note)
    else:
      return render_to_response('vector_analysis.html', {'error' : "Invalid data", "form" : form} )
  else:
    form = BlogForm()
  
  f = zapytanie(find_fun)
  blogi = [x.key for x in f] 


  if blog_note != "":
    start = 'id'
    texts.append(( 'testowt', 'id', blog_note))
    blogi = search(texts, start)
      
  return render_to_response('vector_analysis.html', { 'blogs' : blogi, "form" : form})


